<template>
    <n-layout embedded content-style="padding: 24px;">
        <n-card>
            <n-space vertical :size="12">
                <n-space>
                    <n-button @click="creatInfluecne">
                        新增影响
                    </n-button>
                    <n-button @click="updateInfluecne">
                        修改影响
                    </n-button>
                    <n-button @click="deleteInfluecne">
                        删除影响
                    </n-button>
                </n-space>
                <n-data-table :columns="columns" :data="datas" :pagination="pagination" :bordered="true"
                    :max-height="250" :scroll-x="800" :row-key="rowKey" @update:checked-row-keys="handleCheck"
                    striped />
            </n-space>
        </n-card>

        <!-- 模态化的窗口 -->
        <n-modal v-model:show="showModal" class="custom-card" preset="card" :style="bodyStyle" :title="formTitle"
            size="huge" :bordered="false" :onclose="handleClose">
            <n-form ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto"
                style="margin-top: 20px">
                <!-- 影响名称 -->
                <n-form-item label="影响名称" path="influenceName">
                    <n-input v-model:value="model.influenceName" placeholder="请输入影响名称" clearable />
                </n-form-item>

                <!-- 影响类型 -->
                <n-form-item label="影响类型" path="influenceType">
                    <n-select v-model:value="model.influenceType" :options="typeOptions" placeholder="请选择类型" clearable />
                </n-form-item>

                <!-- 影响中心与定位按钮 -->
                <n-form-item label="影响中心" path="influenceCenterString">
                    <n-space :wrap="false" :size="8">
                        <n-input v-model:value="model.influenceCenterString" placeholder="点击右侧获取位置" readonly style="width: 280px" />
                        <n-button @click="handleGetLocation">
                            <template #icon>
                                <n-icon><location-icon /></n-icon>
                            </template>
                            获取位置
                        </n-button>
                    </n-space>
                </n-form-item>

                <!-- 影响半径 -->
                <n-form-item label="影响半径（米）" path="influenceRaill">
                    <n-input-number v-model:value="model.influenceRaill" :min="0" :precision="0" placeholder="请输入半径" clearable
                        style="width: 100%" />
                </n-form-item>

                <!-- 影响说明 -->
                <n-form-item label="影响说明" path="description">
                    <n-input v-model:value="model.influenceDescription" type="textarea" placeholder="请输入详细说明"
                        :autosize="{ minRows: 3 }" />
                </n-form-item>

                <!-- 提交按钮 -->
                <div style="display: flex; justify-content: flex-end; margin-top: 24px">
                    <n-button type="primary" @click="handleSubmit" :loading="submitting" style="width: 120px">
                        确定
                    </n-button>
                </div>
            </n-form>
        </n-modal>

    </n-layout>
</template>
<script>
import { NButton, NCard, NDataTable, NForm, NFormItem, NIcon, NInput, NInputNumber, NLayout, NModal, NSelect, NSpace, useModal } from 'naive-ui';
import { LocationOutline as LocationIcon } from '@vicons/ionicons5'
import { getCurrentInstance, ref,h } from 'vue';
import { useStore } from 'vuex';
import jq from "jquery";
import commonConstants from '@/common/commonConstants';
import { Cartographic, ScreenSpaceEventHandler, ScreenSpaceEventType,Math as CMath } from 'cesium';
import { reactive } from 'vue';

export default {
    components: {
        NLayout, NCard, NSpace, NButton, NDataTable, NForm, NFormItem, NInput, NModal, NSelect, NIcon,NInputNumber
        , LocationIcon
    },
    props: {
        modal: {
            type: Object
        }
    },
    setup() {

        const um = useModal();
        const showMag = msg=>{
            const mgsModal = um.create({
                title: "提示",
                preset: "card",
                style: {
                    width: "200px"
                },
                content: msg,
                footer: () => h(
                NButton,
                { type: "primary", onClick: () => mgsModal.destroy() },
                    () => "关闭"
                )
            });
        }

        const { proxy } = getCurrentInstance();
        const prentM = proxy.modal;
        const state = useStore().state;
        const scenarioDeduce = state.scenarioDeduce;
        const curViewer = state.curViewer;

        //记录当前选择的影响体
        const curInfluences = ref([]);

        const formTitle = ref("影响体");

        const isEdit = ref(false)

        // 模态框控制
        const showModal = ref(false)
        const formRef = ref(null)
        const submitting = ref(false)

        // 表单模型
        const model = reactive({
            influenceName: '',
            influenceType: null,
            influenceCenter:null,
            influenceCenterString: '',
            influenceRaill: null,
            influenceDescription: ''
        })

        const modelClear = () => {
            Object.assign(model, {
                influenceName: '',
                influenceType: null,
                influenceCenter: '',
                influenceCenterString: '',
                influenceRaill: null,
                influenceDescription: ''
                })
        }


        const columns = ref([
            {
                type: "selection",
                width: 30
            }, {
                title: "影响名称",
                key: "influenceName",
                align: "left"
                // width:100
            }, {
                title: "影响类型",
                key: "influenceType",
                align: "left",
                width: 240
            }, {
                title: "影响中心",
                key: "influenceCenterString",
                align: "left",
                width: 240
            }, {
                title: "影响半径（米）",
                key: "influenceRaill",
                align: "left",
                width: 240
            }, {
                title: "想定描述",
                key: "influenceDescription",
                align: "left"
                // width:200
            }
        ])

        const datas = ref([])
        const curScenario = scenarioDeduce.getCurScenario();
        const influenceManager = curScenario.getInfuenceSource();
        //表格数据获取
        datas.value = influenceManager.getAllInfluence();
        // console.log(datas);
        


        const handleCheck = (rowKeys) => {
            if (rowKeys) {
                rowKeys.forEach(element => {
                    let one = influenceManager.getInfluenceById(element);
                    curInfluences.value.push(one)
                });
            }
           
        }

        //添加影响体
        const creatInfluecne = () => {
            // console.log(model);
            
            formTitle.value = "新增影响体"
            showModal.value = true;
            isEdit.value = false;
        }

        const updateInfluecne = () => {
            //判断选择
            if (!curInfluences.value || curInfluences.value.length == 0) {
                showMag("没有选中的影响体！")
                return
            }
            if (curInfluences.value.length != 1) {
                showMag("不可以同时修改多个影响体！");
                return;
            }
            
            const influ = curInfluences.value[0];
            //不直接修改其本来属性
            Object.assign(model, {
                influenceName: influ.influenceName,
                influenceType: influ.influenceType,
                influenceCenter: influ.influenceCenter,
                influenceCenterString: influ.influenceCenterString,
                influenceRaill: influ.influenceRaill,
                influenceDescription: influ.influenceDescription
                })
            isEdit.value =true;
            formTitle.value = "修改影响体"
            showModal.value = true;
        }

        const deleteInfluecne = () => {
            if (!curInfluences.value || curInfluences.value.length == 0) {
                showMag("没有选中的影响体！")
                return
            }
            const dels = curInfluences.value;
            dels.forEach( d => {
                const index = datas.value.indexOf(d);
                if(index != -1){
                    datas.value.splice(index,1);
                }
            })
            influenceManager.removeInfluences(dels)
        }



        /*******
         * 以下是表单的数据
         */

        // 类型选项
        const typeOptions = [
            { label: '大雾', value: commonConstants.influenceType.dense_fog },
            { label: '大雨', value: commonConstants.influenceType.heavy_rain },
            { label: '大风', value: commonConstants.influenceType.strong_wind },
            { label: '水温', value: commonConstants.influenceType.tsunami },
            { label: '旋涡', value: commonConstants.influenceType.vortex }
        ]

        // 验证规则
        const rules = {
            influenceName: [{ required: true, message: '必须填写影响名称', trigger: 'blur' }],
            influenceType: [{ required: true, message: '必须选择类型', trigger: ["blur", "change"] }],
            influenceCenterString: [{ required: true, message: '必须获取位置信息', trigger: 'change' }],
            influenceRaill: [{ required: true, type: 'number', message: '必须输入有效半径', trigger: 'blur' }]
        }

        let eventHandler = null; // 全局保存事件处理器

        // 左键回调函数（获取位置）
        function leftClickCallback(click) {
            // 坐标转换
            const cartesian = curViewer.camera.pickEllipsoid(
                click.position,
                curViewer.scene.globe.ellipsoid
            );

            if (cartesian) {
                model.influenceCenter = cartesian;
                const cartographic = Cartographic.fromCartesian(cartesian);
                const longitude = CMath.toDegrees(cartographic.longitude);
                const latitude = CMath.toDegrees(cartographic.latitude);

                model.influenceCenterString = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}` 
            }
            // 自动清除键监听
            rightClickCallback()
        }

        // 右键回调函数（取消监听）
        function rightClickCallback() {
            // 移除所有监听
            eventHandler.removeInputAction(ScreenSpaceEventType.LEFT_CLICK);
            eventHandler.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK);
            eventHandler.destroy();

            jq(".n-modal-body-wrapper").css("display","block")
            showModal.value = true;
        }

        // 获取位置方法
        const handleGetLocation = () => {
            //直接就进行监听的开启
            if (curViewer) {
                showModal.value = false;
              
                jq(".n-modal-body-wrapper").css("display","none")

                // 清除已有监听
                if (eventHandler && !eventHandler.isDestroyed()) {
                    eventHandler.destroy();
                }

                // 创建新的处理器
                eventHandler = new ScreenSpaceEventHandler(curViewer.scene.canvas);

                // 左键点击获取位置
                eventHandler.setInputAction(leftClickCallback, ScreenSpaceEventType.LEFT_CLICK);

                // 右键点击取消监听
                eventHandler.setInputAction(rightClickCallback, ScreenSpaceEventType.RIGHT_CLICK);

            } else {
                showMag('Cesium没有渲染成功地球图层!')
            }
        }

        // 提交处理
        const handleSubmit = async () => {
            try {
                submitting.value = true
                await formRef.value.validate()

                // 提交逻辑
                console.log('提交数据:', model)
                if (!isEdit.value) {
                   const m = influenceManager.detectInfluence(model.influenceType,model)
                   if(m){
                    m.renderRange(curViewer)
                    datas.value.push(m)
                   }  
                }else{
                    const influceence = curInfluences.value[0]
                    influceence.handleOptions(model);
                }
                // showMag('提交成功')
                showModal.value = false

                // 重置表单
                modelClear()
            } catch (errors) {
                console.log(errors);
                
                showMag('请检查表单填写是否正确')
            } finally {
                submitting.value = false
            }
        }

        const handleClose = ()=>{
            //关闭Modal
            showModal.value = false;
            modelClear()
        }


        return {
            formRef,
            showModal, rules, formTitle,model,submitting,typeOptions,bodyStyle:{width : "660px"}
            , columns, datas, pagination: { pageSize: 5 }, rowKey: (row) => row.influenceId
            , handleCheck
            , handleSubmit
            , handleClose
            , handleGetLocation
            , creatInfluecne, updateInfluecne, deleteInfluecne
        }
    }
}
</script>